<template>
	<!-- 名片展示与生成 -->
	<div v-show="isShowDom" class="card-dom">
		<!-- 名片 -->
		<div 
		id="user-card" 
		class="center-hint" 
		:style="cardBackground.card"
		v-show="isShowCardDomData"
		:class="showDomClass">
			<div class="center-hint-content" v-show="type === 'normal'">
				<div id="user-card-content">
					<div class="user-card-content-bottom">
						<div class="user-card-info">
							<div class="user-card-info-left">
								<img :src="userInfo.img" class="user-card-img user-img" />
							</div>
							<div class="user-card-info-right">
							<div class="user-card-info-right-top user-card-info-right-chi">
								<span id="user-card-user-name" class="user-name">{{userInfo.name}}</span>
								<span v-show="iconIsShow">
									<span :style="{background: `url(${userInfo.sexImg})`}" class="imgIcon sexIcon"></span>
									<span class="par-help-icon imgIcon sexIcon"></span>
								</span>
							</div>
							<div
								id="user-card-signature"
								class="user-card-info-right-bottom user-card-info-right-chi user-signature"
								v-show="signatureIsShow"
							>{{userInfo.signature}}</div>
							</div>
						</div>
						<div class="user-card-explain">
							<div 
							class="user-card-explain-opt"
							v-for="(item, index) in optionList"
							v-show="item.isShow"
							:key="index"
							>
								<div class="user-card-explain-opt-content">
									<div class="user-card-explain-icon">
										<div class="icon" :style="{background: `url(${item.icon})`}"></div>
									</div>
									<div class="user-card-explain-text">
										<div class="explain-text-top">{{item.name}}</div>
										<div 
										class="user-bs-area explain-text-bottom only-text"
										:class="lineThreeList.indexOf(item.key) >= 0 ? 'line-three' : ''" 
										>{{item.val}}</div>
									</div>
								</div>
							</div>
						</div>
					</div>
				</div>
				<div class="user-card-wechat-qrcode-par">
					<img class="user-card-wechat-qrcode" :src="qrCodeUrl" />
					<div>我的微信名片</div>
				</div>
			</div>
			<div class="custom-center-hint-content" v-show="type === 'custom'">
				<img :src="userInfo.img" class="custom-head-img">
				<!-- <div class="custom-user-name">{{userInfo.name}}</div> -->
				<div class="write-lists">
					<b
					:class="'write-list ' + 'svg-text-' + index"
					v-for="(item, index) in customListData"
					:key="index">
          <svg></svg>
          </b>
				</div>
				<div v-show="isShowQrcode" class="user-card-wechat-qrcode-par">
					<img class="user-card-wechat-qrcode" :src="qrCodeUrl" />
					<div>我的微信名片</div>
				</div>
			</div>
		</div>
		<img 
		@click="closeShowSaveCardHint" 
		v-show="isShowCloseCard" 
		id="close-user-card" 
		:class="closeShowSaveCardClass"
		src="https://www.mrobiji.com/images/close-roundness-white-icon.svg" />
		<img v-show="isShowSaveImg" id="user-card-content-img" :src="savedImg"/>

		<!-- 保存业务名片提示 -->
		<div id="save-card-hint" v-show="isShowSaveCardHint">
			<img class="save-card-hint-img" src="https://www.mrobiji.com/images/save-card-hint-white-icon.svg">
			<span class="save-card-hint-text">请按压名片保存到手机</span>
		</div>
		<van-overlay :show="overlayOneShow" @click="hideOverlayOne" />
		<van-overlay :z-index="3" :show="overlayTwoShow" @click="hideOverlayTwo" />
	</div>
</template>

<script>
// 自定义方法
import { failTextVantToa, loadingVantToa, clearVantToa } from "_projectFn/prompt"
import { enterUserBus, } from "_projectFn/page"
import { getProImg } from "_projectFn/images"
import { getText } from "_commonFn/string"
import { backToTopNow } from "_commonFn/animate"

import TextToSVG from "_commonFn/text-to-svg";
import KaiTi from "../../../assets/fonts/kt.ttf";

// 本地图片
import cardAreaMan from '_assets/img/user-card-area-man.svg'
import cardCompanyMan from '_assets/img/user-card-company-man.svg'
import cardDemandMan from '_assets/img/user-card-demand-man.svg'
import cardPresentationMan from '_assets/img/user-card-presentation-man.svg'
import cardSupplyMan from '_assets/img/user-card-supply-man.svg'
import parHelpRedIcon from "_assets/img/par-help-red-icon.svg"

import cardAreaWomen from '_assets/img/user-card-area-women.svg'
import cardCompanyWomen from '_assets/img/user-card-company-women.svg'
import cardDemandWomen from '_assets/img/user-card-demand-women.svg'
import cardPresentationWomen from '_assets/img/user-card-presentation-women.svg'
import cardSupplyWomen from '_assets/img/user-card-supply-women.svg'

// 自定义组件
import SexIcon from "_components/project/common/SexIcon"
import HelpEarchIcon from "_components/project/common/HelpEarchIcon"

// npm插件
import qrcode from 'qrcode'
import html2canvas from 'html2canvas'

import { Overlay } from 'vant'

import Vue from 'vue'

Vue.use(Overlay)

export default {
	name: 'CardDom',
	props: {
		type: { // 名片内容类型，目前有标准与自定义
			type: String,
			default: 'normal',
		},
		imgUrl: {
			type: String,
			default: '',
		},
		userInfoData: {
			type: Object,
			default: {},
		},
		showDomType: {
			type: String,
			default: 'float'
		},
		isShow: {
			type: Boolean,
			default: false,
		},
		optionWriteList: {
			type: Array,
			default: []
		},
		customList: {
			type: Array,
			default: [],
		},
		isShowCardDom: {
			type: Boolean,
			default: false,
		},
		isShowQrcode: {
			type: Boolean,
			default: true,
		},
	},
	data() {
		return {
			savedImg: this.imgUrl,
			qrCodeUrl: '',
			lineThreeList: ['presentation', 'supply', 'demand'],
			isShowSaveCardHint: false, // 是否显示保存图片提示
			isShowCloseCard: false, // 是否显示关闭图片按钮提示
			isShowSaveImg: false, // 是否显示生成的图片
			isShowCardDomData: this.isShowCardDom,
			overlayOneShow: false,
			overlayTwoShow: false,
			parHelpRedIcon: parHelpRedIcon,
			userInfo: {},
			isShowDom: this.isShow,
			closeShowSaveCardClass: '',
		}
	},
	methods: {
		// 提示保存
		showSave(imgUrl, data) {
			if (location.href.includes('WriteBusCard?type')) {

			} else {
				this.isShowCardDomData = false
			}
			this.checkImgCloseBtnPosi(data.height)
			this.savedImg = imgUrl
			this.overlayOneShow = true
			this.overlayTwoShow = true
			this.isShowSaveCardHint = true // 显示保存图片提示
			this.isShowCloseCard = true // 显示关闭图片按钮提示
			this.isShowSaveImg = true // 显示生成的图片
			setTimeout(() => {
				this.overlayTwoShow = false
				this.isShowSaveCardHint = false
			}, 3000)
		},
		checkImgCloseBtnPosi(cardHeight) {
			const bodyHei = window.innerHeight || document.documentElement.clientHeight
			if (bodyHei < (cardHeight + 30)) {
				this.closeShowSaveCardClass = 'small-phone-position'
			}
		},
		// 隐藏保存图片提示
		closeShowSaveCardHint() {
			this.isShowCloseCard = false
			this.overlayOneShow = false
			this.isShowSaveImg = false // 隐藏生成的图片
		},
		hideOverlayOne() {
			this.overlayOneShow = false
			this.isShowSaveImg = false // 隐藏生成的图片
			this.isShowCloseCard = false
		},
		hideOverlayTwo() {
			this.overlayTwoShow = false
			this.isShowSaveCardHint = false // 隐藏保存图片提示
		},
		addOption({name, val, arr, icon, isShow = true, key}) {
			if (name && val && Array.isArray(arr)) {
				// console.log('push')
				arr.push({ name, val, icon, isShow, key })
			}
		},
		setQrCodeUrl() {
			// console.log('this.userInfoData.userId', this.userInfoData.userId)
			qrcode.toDataURL(`${process.env.PRO_URL}/UserBus?type=userIndex&userId=${this.userInfoData.userId}`, {
				width: 90,
				height: 90,
				margin: 0
			})
			.then(url => {
				this.qrCodeUrl = url
			})
			.catch(err => {
				console.error(err)
			})
		},
		// 执行生成名片
		saveCard() {
			if (location.href.includes('UserBus?type=')) {
				this.isShowCardDomData = true
				this.isShowDom = true
			}
			backToTopNow()
			loadingVantToa({})
			Vue.nextTick()
			.then(() => {
				this.toSaveCard()
			})
		},

		/**
		 * 获取转化实例
		 * @returns {void}
		 * @author Chorin <xiaolinxuan@foxmail.com>
		 * @date 2020-05-05
		 */
		async getKaiTiToSVGInstance(){
			if(!(this.kaitiToSVG instanceof TextToSVG)){
				await TextToSVG.load(KaiTi).then(kaitiToSVG=>{
					this.kaitiToSVG = kaitiToSVG;
				}).catch(e => console.warn("load kaiti warning", e));
			}
			return this.kaitiToSVG;
		},

		/**
		 * 转化为SVG
		 * @returns {void}
		 * @author Chorin <xiaolinxuan@foxmail.com>
		 * @date 2020-05-05
		 */
		async toKaiTiSVG(textList){
			await this.$nextTick().then()
			textList.forEach((text, index) => {
				let textContent = document.querySelector(`.svg-text-${index}`);
				let options  = {fontSize: 22, letterSpacing: .08, attributes: {
					"stroke-width": 1,
					"stroke": "black",
					"fill": "black",
				}}
				this.getKaiTiToSVGInstance()
				.then(kaitiToSVG => {
					let svg = kaitiToSVG.getSVG(text, options)
					textContent.innerHTML = svg
				})
			})
		},

		toSaveCard() {
			const dom = document.getElementById('user-card')
			const style = window.getComputedStyle(dom)
			const height = Number(style.height.replace("px", ''))
			const width = Number(style.width.replace("px", ''))
			// console.log('height', height)
			// console.log('width', width)
			html2canvas(dom, {
				allowTaint: false,
				taintTest: false,
				scale: 3,
				dpi: window.devicePixelRatio * 3,
				useCORS: true,
				width: width, // 设置canvas尺寸与所截图尺寸相同，防止白边
				// background: '#ffffff',
				height: height,
				// scrollX: 0,
				// scrollY: 0,
			})
			.then(canvas => {
				const context = canvas.getContext('2d')
				context.mozImageSmoothingEnabled = false
				context.webkitImageSmoothingEnabled = false
				context.msImageSmoothingEnabled = false
				context.imageSmoothingEnabled = false

				const imgUrl = canvas.toDataURL("image/png", 1)
				this.showSave(imgUrl, {
					height,
				})
				clearVantToa()
			})
			.catch(res => {
				console.log('catch res:', res)
				failTextVantToa()
			})
		},
	},
	computed: {
		showDomClass() {
			// console.log('this.showDomType', this.showDomType)
			// if (this.showDomType === 'float') { // 浮窗
			// 	return 'float'
			// } else { // 正常布局
			// 	return ''
			// }
			return {
				float: this.showDomType === 'float'
			}
		},
		cardBackground() {
			// console.log('this.userInfoData', this.userInfoData)
			return {
				card: { // 背景图片
					background: `url(${this.userInfoData.tempImg}) no-repeat`
				},
				// 男
				man: {
					area: cardAreaMan,
					company: cardCompanyMan,
					demand: cardDemandMan,
					presentation: cardPresentationMan,
					supply: cardSupplyMan,
				},
				women: {
					area: cardAreaWomen,
					company: cardCompanyWomen,
					demand: cardDemandWomen,
					presentation: cardPresentationWomen,
					supply: cardSupplyWomen,
				},
			}
		},
		writeList() {
			return [...this.optionWriteList]
		},
		optionList() {
			const arr = []
			const filterArr = ['icon', 'signature']
			// console.log('this.userInfo.sex', this.userInfo.sex)
			const iconObj = this.userInfo.sex === 1 ? this.cardBackground.man : this.cardBackground.women
			if (this.writeList.length > 0) {
				this.writeList.forEach(item => {
					// console.log('item', item)
					if (filterArr.indexOf(item.key) === -1) {
						this.addOption({
							name: item.name, 
							val: item.val, 
							arr,
							icon: iconObj[item.key], 
							isShow: item.isShow,
							key: item.key,
						})
					}
				})
			} else {
				this.addOption({name: '位置', val: getText(this.userInfo.area), arr, icon: iconObj.area, key: 'area'})
				this.addOption({name: '公司', val: getText(this.userInfo.companyName), arr, icon: iconObj.company, key: 'company'})
				this.addOption({name: '介绍', val: getText(this.userInfo.yourSelf), arr, icon: iconObj.presentation, key: 'presentation'})
				this.addOption({name: '供应', val: getText(this.userInfo.supply), arr, icon: iconObj.supply, key: 'supply'})
				this.addOption({name: '需求', val: getText(this.userInfo.demand), arr, icon: iconObj.demand, key: 'demand'})
			}
			// console.log('arr', arr)
			return arr
		},
		iconIsShow() {
			if (this.writeList.length > 0) {
				const arr = this.writeList
				for(let i = 0; i < arr.length; i++){
					if (arr[i].key == 'icon') {
						return arr[i].isShow
						break
					}
				}
			}
			return true
		},
		signatureIsShow() {
			if (this.writeList.length > 0) {
				const arr = this.writeList
				for(let i = 0; i < arr.length; i++){
					if (arr[i].key == 'signature') {
						return arr[i].isShow
						break
					}
				}
			}
			return true
		},
		customListData() {
			return this.customList
		},
		// userInfo() {
		// 	console.log('this.userInfoData', this.userInfoData)
		// 	return this.userInfoData
		// }
	},
	mounted() {
		// console.log('this.userInfoData', this.userInfoData)
		this.userInfo = this.userInfoData
	},
	activated() {
		// this.checkTempImg()
		this.isShowCloseCard = false // 隐藏关闭图片按钮提示
		this.isShowSaveImg = false // 隐藏生成的图片
		this.overlayOneShow = false
		this.overlayTwoShow = false
	},
	watch: {
		userInfoData: {
			immediate: true,
			deep: true,
			handler(val) {
				// console.log("new val", val)
				this.userInfo = val
				this.setQrCodeUrl() // 设置业务名片二维码
			}
    },
    customList:{
      immediate: true,
      deep: true,
      handler(v, beforeValue){
        v && v.length > 0 && this.toKaiTiSVG(v);
      }
    }
	},
	components: {
		SexIcon,
		HelpEarchIcon,
	}
}
</script>

<style lang="scss" scoped>
.custom-center-hint-content {
	display: flex;
	flex-direction: column;
	align-items: center;
	height: 590px;
	width: 100%;
	border-bottom: 0;
	position: relative;

	.custom-head-img {
		margin-top: 80px;
		border-radius: 50%;
		height: 90px;
		width: 90px;
		margin-bottom: 40px;
	}

	.custom-user-name {
		font-size: 18px;
		line-height: 20px;
		min-height: 40px;
		margin-top: 15px;
		margin-bottom: 40px;
	}

	.write-lists {
		font-size: 22px;
		font-weight: bold;
		color: #000000;
		text-align: center;

		.write-list {
			height: 66px;
			line-height: 4.5;
			display: flex;
			align-items: center;
			justify-content: center;
			overflow: hidden;
			padding: 0 15px;
			font-family: "kaiti", KaiTi, Arial,Verdana,Sans-serif;
		}
	}
}


.card-dom {
	display: flex;
	justify-content: center;
	// padding: 10px 0;

	.float {
		position: fixed;
		top: 50%;
		left: 50%;
		transform: translate(-50%, -50%);
		// background: white;
	}

	/* 用户名片 */
	#user-card {
		width: 90%;
		min-width: 290px;
		max-width: 360px;
		margin-left: 0;
		border-radius: 0;
		border-radius: 0px;
		background-size: 100% 100% !important;

		.center-hint-content {
			border-bottom: 0px;
			width: 100%;
			display: -moz-flex;
			display: flex;
			flex-direction: column;
			align-items: center;
			justify-content: flex-start;
			padding: 0;
			height: 590px;
			width: 100%;
			padding: 35px;
			position: relative;
			background: none;
		}

		#user-card-content {
			width: 100%;
			position: relative;
		}

		.user-card-title {
			line-height: 40px;
			text-align: center;
			background: #0077bf;
			color: white;
			width: 100%;
		}

		.user-card-info {
			height: 60px;
			// padding: 15px 0;
			width: 100%;
			display: flex;
			margin-bottom: 10px;
		}

		.user-card-explain {
			padding-top: 10px;
			padding-bottom: 30px;

			.user-card-explain-opt {
				display: flex;
				align-items: center;
				// max-height: 56px;

				&:not(:first-child) {
					margin-top: 10px;
				}

				.user-card-explain-opt-content {
					width: 100%;
					height: 100%;
					display: flex;

					.user-card-explain-icon {
						flex-shrink: 0;

						.icon {
							background-size: 100% 100% !important;
    						background-repeat: no-repeat !important;
						}

						img {
							width: 35px;
							height: 35px;
							margin-right: 10px;
							margin-bottom: 10px;
						}

						div {
							width: 35px;
							height: 35px;
							margin-right: 10px;
							margin-bottom: 10px;
						}
					}

					.user-card-explain-text {
						width: 100%;
						height: 100%;

						.explain-text-top {
							display: flex;
							min-height: 20px;
							max-height: 40px;
							width: 100%;
							align-items: center;
							font-weight: bold;
						}

						.explain-text-top {
							color: #999999;
						}

						.explain-text-bottom {
							overflow: hidden;
							text-overflow: ellipsis;
							min-height: 20px;
							line-height: 20px;
							max-height: 20px;
							font-weight: bold;
							font-family: 'SimSun';
						}

						.line-three {
							max-height: 60px;
						}
					}
				}
			}
		}

		.user-card-wechat-qrcode-par {
			text-align: center;
			position: absolute;
			bottom: 35px;
			color: white;

			.user-card-wechat-qrcode {
				width: 57px;
				height: 57px;
			}
		}

		.user-card-info-left {
			flex-shrink: 0;
			height: 100%;
			display: flex;
			align-items: center;
			position: relative;
		}

		.user-card-img {
			height: 60px;
			width: 60px;
			border-radius: 50%;
		}

		.user-card-sex {
			display: block;
			background: white;
			width: 18px;
			height: 18px;
			position: absolute;
			bottom: 0px;
			right: 4px;
			border-radius: 50%;

			.user-card-img-sex {
				border-radius: 50%;
				display: block;
				width: 18px;
				height: 18px;
			}
		}

		.user-card-info-right {
			display: flex;
			width: 100%;
			margin-left: 10px;
			flex-direction: column;
			justify-content: center;
		}

		.user-card-info-right-chi {
			// height: 30px;
			line-height: 20px;
			color: #333333;
			overflow: hidden;

			.par-help-icon {
				background: url('../../../assets/img/par-help-red-icon.svg');
			}

			.imgIcon {
				display: inline-block;
				margin-left: 3px;
				width: 15px;
				height: 15px;
				background-size: 100% 100% !important;
				background-repeat: no-repeat !important;
			}

			.sexIcon {
				position: relative;
				top: 2px !important;
			}

			.user-name {
				color: #333333;
			}

			#user-card-user-name {
				font-size: 18px;
				font-weight: bold;
			}
		}

		.user-card-info-right-top {
			max-height: 42px;
		}

		.user-card-opt-list-par {
			margin-top: 10px;

			.user-card-opt-list-find-par {
			color: red;
			font-size: 14px;
			line-height: 30px;
			margin-top: 10px;

				img {
					width: 15px;
				}
			}
		}

		.user-card-opt-list {
			line-height: 28px;
		}

		.user-card-opt-name {
			color: #999999;
		}

		.user-card-opt-content {
			font-weight: bold;
		}

		#save-card {
			height: 50px;
			width: 100%;
			display: flex;
			align-items: center;
			justify-content: center;
			font-size: 16px;
			font-weight: bold;
			color: #999999;
		}

		#user-card-find-par {
			color: red;
			line-height: 35px;
		}
	}
}

// 保存业务名片提示
#save-card-hint {
	.save-card-hint-img {
		width: 30px;
		position: fixed;
		top: 50%;
		left: 50%;
		transform: translate(-50%, -50%);
		z-index: 201;
	}

	.save-card-hint-text {
		color: white;
		font-weight: bold;
		position: fixed;
		top: 50%;
		left: 50%;
		transform: translate(-50%, -50%);
		margin-top: 36px;
		z-index: 201;
	}
}

#close-user-card {
	width: 18px;
    height: 18px;
    position: fixed;
    right: 15px;
    top: 18px;
    cursor: pointer;
    z-index: 8;
}

.small-phone-position {    
	top: 50% !important;
    margin-top: -10px !important;
    right: 1px !important;
}

#user-card-content-img {
	width: 90%;
	min-width: 290px;
	max-width: 360px;
	position: fixed;
	z-index: 2;
	top: 50%;
	left: 50%;
	transform: translate(-50%, -50%);
}
</style>